package org.anrc.poi;

import java.util.ArrayList;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.location.Location;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class PoiList extends Activity {
	ListView poiListView;
	ArrayAdapter<Poi> aa;
	ArrayList<Poi> pois = new ArrayList<Poi>();
	static final private int MENU_UPDATE = Menu.FIRST;
	static final private int POI_DIALOG = 1;
	static final private int MENU_PREFERENCES = Menu.FIRST + 1;
	private static final int SHOW_PREFERENCES = 1;

	Poi selectedPoi;

	PoiReceiver receiver;

	NotificationManager notificationManager;

	@Override
	protected void onResume() {
		notificationManager.cancel(PoiListService.NOTIFICATION_ID);
		IntentFilter filter;
		filter = new IntentFilter(PoiListService.NEW_POI_FOUND);
		receiver = new PoiReceiver();
		registerReceiver(receiver, filter);
		loadPoisFromProvider();
		super.onResume();
	}

	@Override
	public void onPause() {
		unregisterReceiver(receiver);
		super.onPause();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == SHOW_PREFERENCES)
			if (resultCode == Activity.RESULT_OK) {
				updateFromPreferences();
				refreshPois();
			}
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case (POI_DIALOG):
			LayoutInflater li = LayoutInflater.from(this);
			View poiDetailsView = li.inflate(R.layout.poi_details, null);

			AlertDialog.Builder poiDialog = new AlertDialog.Builder(this);
			poiDialog.setTitle("POI informacja");
			poiDialog.setView(poiDetailsView);
			return poiDialog.create();
		}
		return null;
	}

	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		switch (id) {
		case (POI_DIALOG):
			String poiText = "POI " + selectedPoi.getName() + "\n" + "Szer: "
					+ selectedPoi.getLocation().getLatitude() + "\n" + "Dlug: "
					+ selectedPoi.getLocation().getLongitude() + "\n" + "... ";
			AlertDialog quakeDialog = (AlertDialog) dialog;
			quakeDialog.setTitle("Informacja o POI");
			TextView tv = (TextView) quakeDialog
					.findViewById(R.id.poiDetailsTextView);
			tv.setText(poiText);
			break;
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0, MENU_PREFERENCES, Menu.NONE,
				R.string.show_view_poi_settings_string);
		menu.add(0, MENU_UPDATE, Menu.NONE, R.string.update_poi_from_web);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);

		switch (item.getItemId()) {

		case (MENU_PREFERENCES): {
			Intent i = new Intent(this, PoiPreferences.class);
			startActivityForResult(i, SHOW_PREFERENCES);
			return true;
		}
		case (MENU_UPDATE): {
			refreshPois();
			return true;
		}
		}
		return false;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.poi_list_view);

		poiListView = (ListView) this.findViewById(R.id.poiListView);

		poiListView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView _av, View _v, int _index,
					long arg3) {
				selectedPoi = pois.get(_index);
				showDialog(POI_DIALOG);
			}
		});

		int layoutID = android.R.layout.simple_list_item_1;
		aa = new ArrayAdapter<Poi>(this, layoutID, pois);
		poiListView.setAdapter(aa);

		loadPoisFromProvider();

		updateFromPreferences();

		String svcName = Context.NOTIFICATION_SERVICE;
		notificationManager = (NotificationManager) getSystemService(svcName);
	}

	private void refreshPois() {
		startService(new Intent(this, PoiListService.class));
	}

	private void addPoiToArray(Poi _poi) {
		pois.add(_poi);

		aa.notifyDataSetChanged();
	}

	private void loadPoisFromProvider() {
		// Clear the existing poi array
		pois.clear();
		ContentResolver cr = getContentResolver();
		// Return all the saved pois
		Cursor c = cr.query(PoiProvider.CONTENT_URI, null, null, null, null);
		if (c.moveToFirst()) {
			do {
				// Extract the poi details.
				String names = c.getString(PoiProvider.NAME_COLUMN);
				Float lat = c.getFloat(PoiProvider.LATITUDE_COLUMN);
				Float lng = c.getFloat(PoiProvider.LONGITUDE_COLUMN);
				Location location = new Location("dummy");
				location.setLongitude(lng);
				location.setLatitude(lat);

				Poi p = new Poi(names, location);
				addPoiToArray(p);
			} while (c.moveToNext());
		}
		c.close();
	}

	private void updateFromPreferences() {
		SharedPreferences prefs = getSharedPreferences(
				PoiPreferences.USER_PREFERENCES, Activity.MODE_PRIVATE);
		int freqIndex = prefs.getInt(PoiPreferences.PREF_UPDATE_FREQ, 0);
		if (freqIndex < 0)
			freqIndex = 0;

		// TODO
		// boolean autoUpdate =
		// prefs.getBoolean(PoiPreferences.PREF_AUTO_UPDATE,
		// false);
		// Resources r = getResources();

		// int[] freqValues = r.getIntArray(R.array.update_freq_values);

		// int updateFreq = freqValues[freqIndex];
	}

	public class PoiReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			loadPoisFromProvider();
			notificationManager.cancel(PoiListService.NOTIFICATION_ID);
		}
	}

}